package com.zys.sac.core.handler;

import com.zys.sac.core.constant.RequestParam;
import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.util.ServletResponseUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * session方式的成功处理器
 *
 * Created by zhongjunkai on 2022/3/31.
 */
public class SacSessionAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails user = (UserDetails) authentication.getPrincipal();
        HttpSession session = request.getSession();
        session.setAttribute(RequestParam.CURRENT_USER, user);
        List<String> authorities = new ArrayList<>();
        user.getAuthorities().stream().forEach(grantedAuthority -> authorities.add(grantedAuthority.getAuthority()));
        session.setAttribute(RequestParam.AUTHORITIES, authorities);
        ServletResponseUtils.render(response, ServletResponseUtils.result(RequestStatus.SUCCESS.getCode(), RequestStatus.SUCCESS.getMsg()));
    }
}
